import { Component, ElementRef, OnInit, Input, ViewChild, AfterViewInit, EventEmitter } from '@angular/core';
import { TreeModule, TreeNode } from 'primeng/primeng';
import { ActivatedRoute, Router } from '@angular/router';
import { InstitutionService } from '../services/institution.service';
import { Service } from '../../server/server';
import { InstitutionTableComponent } from '../institution/institution-table/institution-table.component';
import { Pagination } from '../../public/serve/pcrudInfo';
import { RemoveTableService } from '../../public/serve/remove-table/remove-table.service';
import { CudTableService } from '../../public/serve/cud-table/cud-table.service';
import { Datatype } from '../institution/institution-table/institution-table.component';
import { roledatas } from '../institution/institution-add-admin/institution-add-admin.component';
import { LocalStorageService } from '../../public/serve/local-storage/local-storage.service';
import { ReplaySubject } from 'rxjs'
import { error } from 'selenium-webdriver';
import * as moment from 'moment';
declare var $: any;

@Component({
  selector: 'app-institution',
  templateUrl: './institution.component.html',
})
export class InstitutionComponent implements OnInit {

  tableNumber: number = 0;

  public treeData: any = [];
  public seletedIds: Array<string> = []
  right: any = {
    "user": {},
    "institution": {}
  };

  constructor(private service: InstitutionService, public activatedRoute: ActivatedRoute, private server: Service, private removeTableService: RemoveTableService, private tableListService: CudTableService, private localStorageService: LocalStorageService, private institutionService: InstitutionService) {
    this.right = $.extend(this.right, server.getRight());
  }


  public isActive = this.server.isActive;

  ngOnInit() {
    this.getParentInfos();
    this.server.eventEmit.subscribe((value: any) => {
      this.isActive = value;
    });
    //获取机构ID
    this.institutioneventEmit = this.server.institutioneventEmit.subscribe((value: any) => {
      this.institutiondate = value;
      //console.log(this.institutiondate)
    });
    //获取按钮状态
    this.institutionbtneventEmit = this.server.institutionbtneventEmit.subscribe((value: any) => {
      this.isbtn = value;
      //console.log(this.isbtn)
    });
    this.selectedItemsSubject = this.institutionService.selectedItemsSubject.subscribe((selectedIds: string[]) => {
      this.seletedIds = selectedIds
    });
    this.reloadSubject = this.institutionService.reloadSubject.subscribe(x => {
      this.table.getTabList(1, this.pageSize, this.superioraddId || "0", this.queryCriteria);
    });
    $(window).keydown((event) => {
      if (event.keyCode == 27) {
        this.exitBoot()
      }
    });
    //所辖用户
    this.institutionofeventEmit = this.server.institutionofeventEmit.subscribe((value: any) => {
      this.treeidname();
    })
  }

  //取消订阅
  public institutioneventEmit: any;
  public institutionbtneventEmit: any;
  public selectedItemsSubject: any;
  public reloadSubject: any;
  public institutionofeventEmit: any;
  ngOnDestroy() {
    if (
      this.institutioneventEmit ||
      this.institutionbtneventEmit ||
      this.selectedItemsSubject ||
      this.reloadSubject ||
      this.institutionofeventEmit
    ) {
      this.institutioneventEmit.unsubscribe();
      this.institutionbtneventEmit.unsubscribe();
      this.selectedItemsSubject.unsubscribe();
      this.reloadSubject.unsubscribe();
      this.institutionofeventEmit.unsubscribe();
    }
  }
  ngAfterViewInit(): void {
    //快捷入口
    this.activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams.id == "add") {
        setTimeout(() => {
          this.add();
          if (document.body.offsetWidth < 1020) {
            this.server.closeindentbutton();
          }
        }, 300);

      }
    });
  }

  ngAfterContentInit() {
    //快捷入口
  }

  ngDoCheck() {
    this.right = $.extend(this.right, this.server.getRight());
    $(".ui-tree-container span:contains('已禁用')").addClass("red animate-time");
  }

  public institutiontime: any;
  public institutiondate: roledatas = {
    roleId: '',
    roleName: ''
  };

  //发射id和name
  public val: any;
  treeidname() {
    if (this.treeData) {
      this.superior = this.superior || this.treeData[0].institutionName || '';
      this.superioraddId = this.superioraddId || this.treeData[0].institutionId;
      this.val = { institutionId: this.superioraddId, institutionName: this.superior }
      this.server.institutiontreeidnameeventEmit.emit(this.val);
    }
  }

  //最上级
  mogami() {
    this.getParentInfos();
    this.table.getTabList(this.pageNumber, this.pageSize, this.superioraddId, this.queryCriteria);
    this.superior = this.treeData[0].institutionName;
    this.superioraddId = this.treeData[0].institutionId;
  }
  public selectedFiles: TreeNode[];
  //树形菜单方法
  getParentInfos(): void {
    this.service.getParentInfos(null).then((data: any) => {
      this.treeData = data;
      this.selectedFiles = [this.treeData[0]];
      this.expandAll();
    })
  }

  //点击选中数据
  public superior: string;
  public superioraddId: string;
  public disableadd: boolean = true;
  nodeSelect(event) {
    //console.log(event.node);
    this.table.getTabList(1, this.pageSize, event.node.institutionId, this.queryCriteria);
    if (event.node.parentId) {
      this.superior = event.node.institutionName;
      this.superioraddId = event.node.institutionId;
      this.val = { institutionId: this.superioraddId, institutionName: this.superior }
      this.server.institutiontreeidnameeventEmit.emit(this.val);
    }
    //禁用新增
    if (this.superior.indexOf('已禁用') >= 0) {
      this.disableadd = false;
    } else {
      this.disableadd = true;
    }
  }
  //
  msgs: any[];
  nodeUnselect(event) {
    this.msgs = [];
    this.msgs.push({ severity: 'info', summary: 'Node Unselected', detail: event.node.label });
  }
  //全部展开
  expandAll() {
    this.treeData.forEach(node => {
      this.expandRecursive(node, true);
    });
  }
  //全部关闭
  collapseAll() {
    this.treeData.forEach(node => {
      this.expandRecursive(node, false);
    });
  }
  private expandRecursive(node: TreeNode, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.children) {
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }

  //引导
  public treeopp: boolean;//引导模式
  public step: number = 0;//步骤
  public title: string;//标题
  public btn: string;//下一步
  public isbtn: boolean = true;//下一步是否点击
  //退出引导
  public exitBoot(): void {
    this.treeopp = false;
    this.step = 0;
    this.isbtn = true;
    $("#mechanismAdd").modal('hide');
    $("#adminAdd").modal('hide');
    $("#ipAdd").modal('hide');
  }
  /**
   * 新增机构 方法 doWhat 检查是不是第一次访问
   */

  public add() {
    this.treeidname();
    if (this.localStorageService.isVisit(1)) {
      // this.step = 666
      $("#mechanismAdd").modal('show');
      this.step = 0;
      this.treeopp = false;
      //通知新增窗口改变状态
      this.server.institutiontwoeventEmit.emit(true);
      // this.treeopp = false;
      // this.title = "新增并填写子机构资料";
      return
    } else {
      this.server.institutiontwoeventEmit.emit(false);
      $("#addtitle").text("新增机构完成退出");
      this.nextStep()
    }
  }
  public nextStep(): void {

    if (this.step <= 5) {
      this.step += 1;
    }

    //第一步
    if (this.step == 1) {
      this.step = 1;
      this.treeopp = true;
      this.btn = "下一步";
      this.title = "选择机构目录";
    }
    //第二步
    if (this.step == 2) {
      $("#mechanismAdd").modal('show');
      this.treeopp = false;
      this.title = "新增并填写子机构资料";
    }
    //第三步
    if (this.step == 3 && this.institutiondate.roleId !== '') {
      $("#mechanismAdd").modal('hide');
      $("#adminAdd").modal('show');
      this.title = "为机构添加管理员";
      this.isbtn = true;
    } else if (this.step == 3 && this.institutiondate.roleId == '') {
      this.step = 2;
      //prompt

      this.server.prompt = { prompt: true, success: false, fail: true, promptStatement: "请添加完获取所属机构" };
      this.server.promptclose;
      this.isbtn = false;
    }
    //第四步
    if (this.step == 4) {
      this.isbtn = true;
      $("#adminAdd").modal('hide');
      $("#ipAdd").modal('show');
      this.title = "设置IP白名单规则";
    }
    //第五步(完成)
    if (this.step == 5) {
      $("#ipAdd").modal('hide');
      this.treeopp = true;
      this.title = "完成";
      this.btn = "完成";
    }
    if (this.step == 6) {
      this.step = 0;
      this.treeopp = false;
    }
  }
  //接收add引导值
  public stepadds: number;
  stepadd(stepadds) {
    this.step = stepadds.step;
    this.treeopp = stepadds.treeopp;
    this.btn = stepadds.btn;
    this.title = stepadds.title;
  }

  //导入table
  @ViewChild("table")
  table: InstitutionTableComponent;
  // 表格
  public totalItems: number;
  ParentList(totalItems: number) {
    this.totalItems = totalItems;
  }

  //详情
  public tabVal: Datatype;
  ParentDetails(tabVal: Datatype) {
    //console.log(tabVal)
    this.tabVal = tabVal;
    if (this.tabVal && this.tabVal.validDate) {
      this.tabVal.validDate = moment(this.tabVal.validDate).isValid() ? moment(this.tabVal.validDate).toDate() : null
    }
    this.treeidname();
  }

  //新增
  public newly_added_result_code: string;
  ParentAdd(result_code: string) {
    this.table.getTabList(this.pageNumber, this.pageSize, this.superioraddId, this.queryCriteria);
    this.getParentInfos();
  }

  // 修改
  public edit_result_code: string;
  ParentUpdate(result_code: string) {
    this.table.getTabList(this.pageNumber, this.pageSize, this.superioraddId, this.queryCriteria);
    this.getParentInfos();
  }

  //删除click
  public deletes() {
    if (this.removeTableService.getRemoveTableId.length == 0) {
      this.server.prompt = { prompt: true, success: false, fail: false, promptStatement: "请选中要删除的数据!" }
      this.server.promptclose;
    } else {
      $("#delete").modal('show');
    }
  }
  //删除
  public remove_result_code: string;
  ParentDelete(result_code: string) {
    this.table.getTabList(1, this.pageSize, this.superioraddId || "0", this.queryCriteria);
    this.table.cancelSelectAll();
    this.getParentInfos();
  }

  // 当前页（默认为第一页）
  public pageNumber: number = 1;
  // 每页显示多少条数据（默认每页显示20条）
  public pageSize: number = 20;
  // id
  public id: string = '0';
  // 分页
  public pagination: Pagination;
  isLoadTableFromPaginationHandler(pagination: Pagination) {
    this.pagination = pagination;

    this.pageNumber = this.pagination[0].pageNumber;
    this.pageSize = this.pagination[0].pageSize;
    this.id = this.pagination[0].id;

    this.tableNumber = (pagination[0].pageNumber - 1) * pagination[0].pageSize;

    this.table.getTabList(this.pageNumber, this.pageSize, '12aa1c87305f4271a90bffeb28315ca2', this.queryCriteria);
  }


  // public disable(): void {
  //   console.log(this.institutionService.selectedItems)
  //   this.institutionService.enableInstitution(this.institutionService.selectedItems,0).subscribe(res=>{
  //     console.log(res)
  //     this.institutionService.reloadSubject.next("RELOAD")
  //   })
  // }
  // public restart():void{
  //   this.institutionService.reloadSubject.next("RELOAD")
  // }
  public enable(enable: number) {
    //console.log(enable)
    this.institutionService.enableInstitution(this.institutionService.selectedItems, enable).subscribe((response: any) => {
      let res = response.json()
      if (res.result_code == "0000") {
        //this.institutionService.reloadSubject.next("RELOAD");
        this.table.getTabList(this.pageNumber, this.pageSize, this.superioraddId, this.queryCriteria);
        this.getParentInfos();
        this.server.prompt = { prompt: true, success: true, fail: false, promptStatement: res.message }
        this.server.promptclose;
      } else {
        this.server.prompt = { prompt: true, success: false, fail: true, promptStatement: res.message }
        this.server.promptclose;
      }
    })
  }

  public queryCriteria: string;
  //查询
  search() {
    this.table.getTabList(this.pageNumber, this.pageSize, this.superioraddId, this.queryCriteria);
  }
  //响应搜索
  changesearch() {
    this.search();
  }
}
